package cn.xdf.demo01;

import cn.xdf.entity.Goods;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class Demo02_API查询 {

    private HttpSolrServer solrServer=new HttpSolrServer("http://localhost:9090/solr/Goods");


    //增
    @Test
    public void test01() throws Exception{

        //构建查询条件
        SolrQuery solrQuery=new SolrQuery("title:华为智能小米笔记本");

        //开启高亮
        solrQuery.setHighlight(true);

        //设置高亮域
        solrQuery.addHighlightField("name");
        solrQuery.addHighlightField("title");

        //设置高亮的前后缀
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");


//        solrQuery.addFilterQuery("price:[2000 TO 8000]");
//
//        solrQuery.addSort("price", SolrQuery.ORDER.desc);

//        solrQuery.setStart(1);//开始
//        solrQuery.setRows(3);//往后查询
//        solrQuery.setFields("id,name,title");//fl只查询什么字段

        //执行查询
        QueryResponse response = solrServer.query(solrQuery);

        //获取结果集变成good实体类对象(获取原始数据)
        List<Goods> goodsList = response.getBeans(Goods.class);

//        for(Goods goods:goodsList){
//            System.out.println(goods);
//        }
        //获取高亮数据
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

        //遍历高亮数据
//        for(String docId:highlighting.keySet()){
//
//            //根据文档id获取这篇文档的高亮数据
//            Map<String, List<String>> docHigh = highlighting.get(docId);
//
//            List<String> nameList = docHigh.get("name");
//            List<String> titleList = docHigh.get("title");
//
//            if(nameList !=null){
//                System.out.println("name域的数据："+nameList.get(0));
//            }
//
//            if(titleList !=null){
//                System.out.println("title域的数据："+titleList.get(0));
//            }

        for(Goods goods:goodsList){

            //遍历原始数据，拿原始数据去高亮数据里面找，看有没对应的高亮数据

            Map<String, List<String>> docHigh = highlighting.get(goods.getId());

            List<String> nameList = docHigh.get("name");
            List<String> titleList = docHigh.get("title");

            if(nameList!=null){

                //如果有高亮数据，用高亮数据替换原始数据
                goods.setName(nameList.get(0));
            }

            if(titleList!=null){
                goods.setTitle(titleList.get(0));
            }

            System.out.println(goods);

        }




        }


    }


